//
//  Date+Extension.swift
//  WBDemo
//
//  Created by Meng on 17/2/14.
//  Copyright © 2017年 demo. All rights reserved.
//

import Foundation

extension Date {
    // 字符串转date
    static func createDate(timeStr: String, formatterStr: String) -> Date {
        let formatter = DateFormatter()
        formatter.dateFormat = "EE MM dd HH:mm:ss Z yyyy"
        formatter.locale = Locale(identifier: "en")
        return formatter.date(from: timeStr)!
    }
    // 生产当前时间对应的字符串
    func descriptionStr() -> String {
        /**
         刚刚(一分钟内)
         X分钟前(一小时内)
         X小时前(当天)
         昨天 HH:mm(昨天)
         MM-dd HH:mm(一年内)
         yyyy-MM-dd HH:mm(更早期)
         */
        let formatter = DateFormatter()
        formatter.locale = Locale(identifier: "en")
        
        let lCalendar = Calendar.current
        if lCalendar.isDateInToday(self) {
            let timeInterval = Int(Date().timeIntervalSince(self))
            if timeInterval < 60 {
                return "刚刚"
            } else if timeInterval < 60 * 60 {
                return "\(timeInterval / 60)分钟前"
            } else if timeInterval < 60 * 60 * 24 {
                return "\(timeInterval / (60 * 60))小时前"
            }
        } else if lCalendar.isDateInYesterday(self) {
            formatter.dateFormat = "昨天 HH:mm"
        } else {
            let comps = lCalendar.dateComponents([.year], from: self, to: Date())
            if comps.year! >= 1 {
                formatter.dateFormat = "yyyy-MM-dd HH:mm"
            } else {
                formatter.dateFormat = "MM-dd HH:mm"
            }
        }
        return formatter.string(from: self)
    }
}
